package com.iris.live.services.interceptors;

import com.iris.live.services.common.JsonObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @Description:负责记录请求输入参数和响应参数的插件
 * @author: Tony.Zhang
 * @Date: 2017-01-27 8:58
 **/

@EnableAspectJAutoProxy
@Aspect
@Component
public class RequestAspect {
    private static final Logger logger = LoggerFactory.getLogger(RequestAspect.class);

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controllerAspect(){	}

    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            StringBuffer message = new StringBuffer();

            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Parameter[] parameters = method.getParameters();

            Object[] args = joinPoint.getArgs();
            if (args != null) {
                for (int index = 0; index < args.length; index++) {
                    Object arg = args[index];
                    if (!(arg instanceof HttpServletRequest || arg instanceof HttpServletResponse)) {
                        Parameter parameter = parameters[index];
                        message.append(parameter.getName()).append("=").append(JsonObjectUtils.writeAsJson(arg));
                    }
                }
            }

            if (logger.isInfoEnabled()) {
                logger.info(message.toString());
            }
        }catch(Exception exc){
            logger.error("拦截器异常。", exc);
        }
    }

    @AfterReturning(pointcut="controllerAspect()", returning="returnVal")
    public void afterReturn(JoinPoint joinPoint, Object returnVal){
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("returnValue={}", JsonObjectUtils.writeAsJson(returnVal));
            }
        }catch(Exception exc){
            logger.error("拦截器异常", exc);
        }
    }
}
